import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterstudyapplast/business/viewmodels/article_collect_viwemodel.dart';
import 'package:flutterstudyapplast/services/service_locator.dart';
import 'package:toast/toast.dart';

class CollectAddWebsite extends StatefulWidget {
  @override
  _CollectAddWebsiteState createState() => _CollectAddWebsiteState();
}

class _CollectAddWebsiteState extends State<CollectAddWebsite> {
  String _name;
  String _url;
  final globalKey  = GlobalKey<FormState>();
  ArticleCollectViewModel _articleCollectViewModel = serviceLocator<ArticleCollectViewModel>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("收藏网址"),),
      body: Form(
        key: globalKey,
        child: ListView(
          padding: EdgeInsets.all(20),
          children: <Widget>[
            TextFormField(
              autofocus: true,
              decoration: InputDecoration(labelText: "名称"),
              validator: (value){
                if(value.trim().isEmpty){
                  return "请输入名称";
                }
                _name = value.trim();
              },
            ),
            TextFormField(
              initialValue: "http://",
              decoration: InputDecoration(
                labelText: '地址',
              ),
              keyboardType: TextInputType.url,
              validator: (String value) {
                if (value.trim().isEmpty) {
                  return '请输入收藏网站地址';
                }
                _url = value.trim();
              },
            ),
            Container(
              height: 45.0,
              margin: EdgeInsets.only(top: 18.0, left: 8.0, right: 8.0),
              child: RaisedButton(
                child: Text(
                  '收藏',
                  style: TextStyle(fontSize: 18.0, color: Colors.white),
                ),
                color: Theme.of(context).primaryColor,
                onPressed: ()=>_doAdd(context),
              ),
            )
          ],
        ),
      ),
    );
  }
  _doAdd(context) async{
    if(globalKey.currentState.validate()){
      showDialog(context: context, barrierDismissible: false, builder: (_) {
        return Center(child: CircularProgressIndicator(),);
      });

      //对话框dismiss
      Navigator.pop(context);
      var result = await _articleCollectViewModel.collectWebsite(_name, _url);
      if(result == null){
        Toast.show("收藏失败！！", context,gravity:Toast.CENTER);
      }else{
        Navigator.pop(context,result);
      }
    }
  }
}
